package com.ysucloud.api.service.impl;

import com.ysucloud.api.DTO.CartDTO;
import com.ysucloud.api.dataobject.ProductInfo;
import com.ysucloud.api.enums.ProductStatusEnum;
import com.ysucloud.api.enums.ResultEnum;
import com.ysucloud.api.exception.ProductException;
import com.ysucloud.api.repository.ProductInfoRepository;
import com.ysucloud.api.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description: api
 * Created by aininot260 on 2019/6/27 16:45
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findList(List<Integer> productIdList) {
        return productInfoRepository.findByProductIdIn(productIdList);
    }


    @Override
    /**
     * 会抛出空查询错误 NoSuchElementException
     */
    public void decreaseStock(List<CartDTO> cartDTOList)
    {
        /** 按照传过来的列表修改库存 */
        for(CartDTO cartDTO: cartDTOList)
        {
            ProductInfo productInfo = productInfoRepository.findById(cartDTO.getProductId()).get();
            Integer result=productInfo.getProductStock()-cartDTO.getProductQuantity();
            if(result<0)
            {
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }
    }
}
